﻿using Admin.Core.Common.Attributes;
using Admin.Core.Common.Auth;
using Admin.Core.Common.Input;
using Admin.Core.Common.Output;
using Admin.Core.Common.ParamInput;
using Admin.Core.Model.Xsproject;
using Admin.Core.Repository.Admin;
using Admin.Core.Repository.Xsproject.TaskItem;
using Admin.Core.Service.Xsproject.TaskItem.Input;
using Admin.Core.Service.Xsproject.TaskItem.Output;
using AutoMapper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Admin.Core.Service.Xsproject.TaskItem
{
    public class TaskItemService: ITaskItemService
    {
        private readonly IUser _user;
        private readonly IMapper _mapper;
        private readonly ITaskItemRepository _taskItemRepository;
        private readonly IDictionaryRepository _dictionaryRepository;
        public TaskItemService(IUser user, IMapper mapper
            , ITaskItemRepository taskItemRepository
            , IDictionaryRepository dictionaryRepository
            )
        {
            _user = user;
            _mapper = mapper;
            _taskItemRepository = taskItemRepository;
            _dictionaryRepository = dictionaryRepository;
        }




        public async Task<IResponseOutput> AddAsync(TaskItemAddInput input)
        {
            string sql = $@"select t.id from XS_TASKITEM t where t.tenantid = {_user.TenantId} and t.isdeleted = 0 and projectId = {input.ProjectId} and taskid = {input.ParentId}";
            var rs = await _taskItemRepository.Orm.Ado.QueryAsync<long>(sql);
            var entity = _mapper.Map<TaskItemEntity>(input);
            entity.TenantId = _user.TenantId;
            entity.ParentId = rs[0];
            entity.TaskFlag = 0;
            var id = (await _taskItemRepository.baseRepository.InsertAsync(entity)).Id;
            return ResponseOutput.Result(id > 0);
        }
        public async Task<IResponseOutput> GetTaskItemAsync(long id)
        {
            var entity = await _taskItemRepository.baseRepository.Select.Where(a => a.Id.Equals(id)).Count(out var total).ToOneAsync(a=>new TaskItemGetOutput { 
             ParentId = a.Parent.TaskId
            });
            if (total > 0)
            {
                return ResponseOutput.Ok(entity);
            }
            else
            {
                return ResponseOutput.NotOk("当前任务状态异常");
            }

        }

        

        public async Task<IResponseOutput> UpdateTaskItemAsync(TaskItemUpdateInput input)
        {
            //if (!(input?.Id > 0))
            //{
            //    return ResponseOutput.NotOk();
            //}
            //var entity = await _taskItemRepository.GetAsync(input.Id);
            //if (!(entity?.Id > 0))
            //{
            //    return ResponseOutput.NotOk("任务状态异常！");
            //}
            //input.ParentId = entity.ParentId;
            //_mapper.Map(input, entity);
            //await _taskItemRepository.UpdateAsync(entity);
            return ResponseOutput.Ok();
        }

        /// <summary>
        /// 获取指定字典项的
        /// </summary>
        /// <returns></returns>
        private async Task<List<DicItemOut>> GetDicModelAsync()
        {
            string sql = $@"select a.id , a.name name , a.value  ,a.code  from AD_DICTIONARY a where a.enabled = 1 and a.isdeleted = 0 and a.parentid = (select b.id from AD_DICTIONARY b where b.code = 'PLP_MODEL' 
and b.enabled = 1 and b.isdeleted = 0  and b.tenantid = {_user.TenantId})"; 
            var result = await _dictionaryRepository.Orm.Ado.QueryAsync<DicItemOut>(sql);
            return result;
        }



        /// <summary>
        /// 初始化模板
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [Transaction]
        public async Task<IResponseOutput> InitAsync(CommonIdInput input)
        {
            var list = await GetDicModelAsync();

            foreach (var m in list)
            {
                TaskItemEntity entity = new TaskItemEntity
                {
                    FlowId = m.Value,
                    Sort = m.Code,
                    ParentId = 0,
                    ProjectId = input.id,
                    TenantId = _user.TenantId,
                    Status = -1,
                    TaskFlag = null,
                    TaskId = m.Id
                };
                await _taskItemRepository.baseRepository.InsertAsync(entity);
            }

            //var entity = _mapper.Map<ProjectEntity>(input);
            //entity.TenantId = _user.TenantId;
            //var id = (await _projectRepository.baseRepository.InsertAsync(entity)).Id;
            return ResponseOutput.Result(true);
        }


        public async Task<IResponseOutput> GetAllDetailPageAsync(long wlId)
        {
            var list = await _taskItemRepository.baseRepository.Select
                .Where(a => a.ProjectId.Equals(wlId))
                .Count(out var total)
                .ToListAsync((a) => new TaskItemListOutput
                {
                    ProjectId = a.ProjectId,
                    Name = a.Task.Name,
                    Status = a.Status == -1 ? "未就绪" : a.Status == 0 ? "待处理" : a.Status == 1 ? "进行中" : a.Status == 2 ? "已完成" : "",
                    Id = a.Id,
                    ParentId = a.ParentId,
                    ResponName = a.ResponId,
                    Sort = a.Task.Sort,
                    PlanBeginDate = a.PlanBeginDate,
                    PlanEndDate = a.PlanEndDate,
                    TaskFlag = a.TaskFlag == 0 ? "未处理" : a.TaskFlag == 1 ? "处理中" : a.TaskFlag == 2 ? "已完成" : "",
                });
            if (total == 0)
            {
                
            }
            var parentlist = list.Where(x => x.ParentId == 0).ToList();
            parentlist.ForEach(x =>
            {
                x.Children = list.Where(z => z.ParentId == x.Id).ToList();
            });
            return ResponseOutput.Ok(parentlist);
        }

        /// <summary>
        /// 获取gantt源数据
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<IResponseOutput> GetGanttDataAsync(long id)
        {
            var list = await _taskItemRepository.baseRepository.Select
                .Where(a => a.ProjectId.Equals(id))
                .Count(out var total)
                .ToListAsync((a) => new TaskGanttOutput
                {
                    Id = a.Id,
                    Parent = a.ParentId,
                    Text = a.Task.Name,
                    Start_date = a.Id==0?null:a.PlanBeginDate.Value.ToString("dd-MM-yyyy"),
                    End_date = a.Id==0?null:a.PlanEndDate.Value.ToString("dd-MM-yyyy"),
                    Open = true,
                    Progress = 0,
                    Remark = a.Remark,
                    PersonName = a.Respon.NickName,
                    Warn = false,
                });
            if (total == 0)
            {
                return ResponseOutput.NotOk("该项目还生成模板！");
            }

            var listact = await _taskItemRepository.baseRepository.Select
               .Where(a => a.ProjectId.Equals(id))
               .Where(a=>a.ActualBeginDate!=null)
               .Count(out var total1)
               .ToListAsync((a) => new TaskGanttOutput
               {
                   Id = a.Id*30,
                   Parent = a.Id,
                   Text = a.Task.Name,
                   Open = true,
                   Start_date = a.ActualBeginDate.Value.ToString("dd-MM-yyyy"),
                   End_date= a.ActualEndDate.Value.ToString("dd-MM-yyyy"),
                   Progress = a.Progress/100,
                   Remark = a.Remark,
                   PersonName = a.Respon.NickName,
                   Warn = false,
               });
            listact.ForEach(x => x.Text = "实际进度");
            list.AddRange(listact);
            //parentlist.ForEach(x =>
            //{
            //    x.Children = list.Where(z => z.ParentId == x.Id).ToList();
            //});
            return ResponseOutput.Ok(list);
        }

        /// <summary>
        /// 获取指定字典项的下拉
        /// </summary>
        /// <returns></returns>
        public async Task<IResponseOutput> GetTaskItemsAsync(long id,long projectId,long? taskId)
        {
            string filterSql = string.Empty;
            if (taskId!=null)
            {
                 filterSql = $@" and a.taskid!= {taskId}";
            }
            string sqlstr = $@"select a.taskid from   xs_taskitem a where  a.tenantid = {_user.TenantId} and a.isdeleted=0 and 
                            a.projectid = {projectId} 
                            {filterSql}
                            and a.parentid =(select b.Id from  xs_taskitem b 
                            where b.taskid= {id} and b.projectid =  {projectId} 
                            and b.tenantid = {_user.TenantId} and b.isdeleted = 0)";
            var rs = await _dictionaryRepository.Orm.Ado.QueryAsync<long>(sqlstr);

            string sql = $@"select a.id value,a.name label from AD_DICTIONARY a where a.enabled = 1 and a.isdeleted = 0 and a.parentid = (select b.id from AD_DICTIONARY b where b.id ={id}
and b.enabled = 1 and b.isdeleted = 0  and b.tenantid = {_user.TenantId})";
            var result = await _dictionaryRepository.Orm.Ado.QueryAsync<CommonCom>(sql);
            var ls = result.Where(x => !@rs.Contains(x.Value)).ToList();
            return ResponseOutput.Ok(ls);
        }



        public async Task<IResponseOutput> UpdateTaskAsync(List<TaskItemUpdateInput> uplist)
        {
            List<long> ls = new List<long>();
            uplist.ForEach((x) => {
                ls.Add(x.Id);
            });
            var rsList = await _taskItemRepository.baseRepository.Select.Where(x => ls.Contains(x.Id)).ToListAsync();
            uplist.ForEach((z) =>
            {
                rsList.ForEach((x) =>
                {
                    if (z.Id == x.Id)
                    {
                        x.PlanBeginDate = z.PlanBeginDate;
                        x.PlanEndDate = z.PlanEndDate;
                        x.ResponId = z.ResponName;
                    }
                });
            });
            //var list = _mapper.Map<List<TaskItemEntity>>(uplist);
            var rs = await _taskItemRepository.baseRepository.UpdateAsync(rsList);
            return ResponseOutput.Result(rs> 0);
        }
        public async Task<IResponseOutput> PageAsync(PageInput<ConmonFilterInput> input)
        {
            var key = input.Filter?.Name;
            var list = await _taskItemRepository.baseRepository.Select
            .WhereIf(key.NotNull(), a => a.Task.Name.Contains(key))
            .Where(x=>x.ResponId.Equals(_user.Id))
            .Where(x=>x.TaskFlag == 0 || x.TaskFlag ==1 || x.TaskFlag == 2)
            .Where(x=>x.Parent.Status==0 ||x.Parent.Status==1|| x.Parent.Status == 2)
            .Count(out var total)
            .OrderByDescending(true, c => c.Id)
            .Page(input.CurrentPage, input.PageSize)
            .ToListAsync(a => new TaskItemExOutput
            {
                ParentName = a.Parent.Task.Name,
                ResponName = a.Respon.NickName,
                TaskName = a.Task.Name,
                ProjectName = a.Project.Name,
                TaskFlag = a.TaskFlag == 0 ? "待处理" : a.TaskFlag == 1 ? "处理中" : "已完成",
            });
            //list.ForEach(x => {
            //    x.Progress = decimal.Round(x.Progress, 2);
            //});
            //var projectList = _mapper.Map<List<ProjectListOutput>>(list);
            var data = new PageOutput<TaskItemExOutput>()
            {
                List = list,
                Total = total
            };
            //var data = new VxePageOutPut<TaskItemExOutput>()
            //{
            //    Result = list,
            //    Page = new VxePage { currentPage = input.CurrentPage, pageSize = input.PageSize, total = total, totalResult = total }
            //};
            return ResponseOutput.Ok(data);
        }

        /// <summary>
        /// 开启任务
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [Transaction]
        public async Task<IResponseOutput> TaskBeginAsync(TaskBeginInput input)
        {
            if (!(input?.Id > 0))
            {
                return ResponseOutput.NotOk();
            }
            var entity = await _taskItemRepository.GetAsync<TaskItemEntity>(input.Id);
            if (!(entity?.Id > 0))
            {
                return ResponseOutput.NotOk("任务不存在！");
            }
            entity.ActualBeginDate = input.ActualBeginDate;
            entity.ActualEndDate = input.ActualEndDate;
            entity.TaskFlag = 1;
            var rs = await _taskItemRepository.GetAsync<TaskItemEntity>(entity.ParentId.Value);
            if(rs.Status == 0)
            {
                rs.Status = 1;
                await _taskItemRepository.UpdateAsync(rs);
            }
            await _taskItemRepository.UpdateAsync(entity);
            return ResponseOutput.Ok();
        }


        /// <summary>
        /// 获取物料类型
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<IResponseOutput> GetUpTaskAsync(long id)
        {
            var result = await _taskItemRepository.GetAsync<TaskItemEntity>(id);
            TaskItemUpOutput output = new TaskItemUpOutput
            {
                ActualEndDate = result.ActualEndDate.Value,
                TaskId = result.Id,
                Remark = "",
                FileName = "",
                FilePath = "",
                Progress = result.Progress,
                TaskFlag = result.TaskFlag.Value
            };
            return ResponseOutput.Ok(output);
        }
    }
}
